﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Marmat.Forms.Skin
{
    internal class DragFormImplementation
    {
        private readonly Control dragControl;
        private Point dragLocation;
        private static readonly List<Control> controls = new List<Control>();

        internal DragFormImplementation(Control dragControl)
        {
            this.dragControl = dragControl;
        }

        internal void Start()
        {
            if (controls.Contains(this.dragControl))
                throw new Exception("不支持重复开启");
            controls.Add(this.dragControl);
            this.dragControl.MouseDown += this.DragControl_MouseDown;
            this.dragControl.MouseMove += this.DragControl_MouseMove;
            this.dragControl.MouseUp += this.DragControl_MouseUp;
            this.dragControl.Disposed += this.DragControl_Disposed;
        }

        internal void Close()
        {
            if (!controls.Contains(this.dragControl))
                throw new Exception("未开启拖动，无需关闭拖动模式");
            controls.Remove(this.dragControl);
            this.dragControl.MouseDown -= this.DragControl_MouseDown;
            this.dragControl.MouseMove -= this.DragControl_MouseMove;
            this.dragControl.MouseUp -= this.DragControl_MouseUp;
            this.dragControl.Disposed -= this.DragControl_Disposed;
        }

        private void DragControl_Disposed(object sender, EventArgs e)
        {
            controls.Remove(sender as Control);
        }

        private void DragControl_MouseUp(object sender, MouseEventArgs e)
        {
            System.Windows.Forms.Form form = this.dragControl.FindForm();
            if (form.Top < 0)
                form.Top = 0;
        }

        private void DragControl_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.dragLocation = e.Location;
            }
        }

        private void DragControl_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                System.Windows.Forms.Form form = this.dragControl.FindForm();
                form.Location = new Point(form.Location.X + e.X - dragLocation.X, form.Location.Y + e.Y - dragLocation.Y);
            }
        }
    }
}
